package example.lesson07_03;

// 泛型：参数化类型， 把 类型 作为一种参数
public class TestGenerics {

    // Ctrl + Shift + ?
    /*static Person getMin(Person[] arr) {
        Person min = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i].age < min.age) {
                min = arr[i];
            }
        }
        return min;
    }*/

    // 泛型方法, <类型参数列表> 返回类型 方法名(参数列表)
    // extends 类型约束， T 类型 必须是 Person 类型或其子类
    static <T extends Person> T getMin(T[] arr) {
        T min = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i].age < min.age) {
                min = arr[i];
            }
        }
        return min;
    }

    public static void main(String[] args) {
        Student[] arr = new Student[3];
        arr[0] = new Student(10, "ZhangSan", "zsc");
        arr[1] = new Student(30, "LiSi", "zsc");
        arr[2] = new Student(20, "WangWu", "zsc");
        // Student min = (Student)getMin(arr);
        // 使用泛型后， 无需强制类型转换，支持编译时检查，提高代码复用
        Student min = getMin(arr); // Student -> T
        System.out.println("min:" + min);

        ArrayTool<Student> tool = new ArrayTool<>();
        Student max = tool.getMax(arr);
        System.out.println("max:" + max);
    }
}

// 泛型类, class 类名<类型参数列表>
class ArrayTool<T extends Person> {
    // 类型参数 T， 只能用在 实例成员中
    T getMax(T[] arr) {
        T max = arr[0];
        for(T elem : arr) {
            if(elem.age > max.age) {
                max = elem;
            }
        }
        return max;
    }
}

class Person {
    public int age;
    public String name;

    Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "age:" + age + ", name:" + name;
    }
}

class Student extends Person {
    public String school;

    Student(int age, String name, String school) {
        super(age, name);
        this.school = school;
    }

    @Override
    public String toString() {
        return super.toString() + ",school:" + school;
    }
}
